import express from 'express'
import { getStore } from '../store/index'
import routes from '../Routes'
import { render } from './util.js'
import { matchRoutes } from 'react-router-config'
import proxy from 'express-http-proxy'
//虚拟dom是真实dom的JavaScript的对象映射
// 1.可以提升页面渲染性能
// 2.方便服务器端渲染

//客户端渲染在浏览器上执行
//服务端渲染，消耗的是服务器的性能


const app = express()
app.use(express.static('public'))//当请求的是一个静态文件，就去public这个文件夹下找

app.use('/api', proxy('http://47.95.113.63', {
  proxyReqPathResolver: function (req) {
    return `/ssr/api${req.url}`
  }
}));



app.get('*', (req, res) => { 
  const store = getStore(req)
  //获取异步数据并且对store进行填充
  //store 中具体填充什么，需要根据当前用户请求的地址路由加载不同的data
  //根据路由路径给store添加数据
  //筛选出当前路由
  const matchedRoutes = matchRoutes(routes, req.path)
  const promise = [];
  matchedRoutes.forEach(router => {
    if(router.route.loadData){
      promise.push(router.route.loadData(store))
    }
  })
  Promise.all(promise).then(() => {
    res.send(render(req, store, routes))
  })
})

const server = app.listen(3000, 'localhost', () => {
  var host = server.address().address
  var port = server.address().port //输出端口号

  console.log(`NODE START AT ${host}:${port}`)
})